package com.victor.modular.system.controller;

import com.alibaba.fastjson.JSON;
import com.victor.common.constant.Const;
import com.victor.common.constant.cache.CacheKey;
import com.victor.common.constant.factory.ConstantFactory;
import com.victor.common.controller.BaseController;
import com.victor.common.persistence.model.UsersImages;
import com.victor.core.shiro.ShiroKit;
import com.victor.core.util.FileUtil;
import com.victor.core.util.ToolUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Auther:Victor
 * @Description:图片控制器
 * @Date:Create in 9:56 2018/4/21
 * @Modified By:
 */
@Controller
@RequestMapping("/uploadImage")
public class ImageUploadController extends BaseController {
    static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    static Object lockObj = new Object();
    private static String PREFIX = "/system/uploadImage/";

    /**
     * 跳转到用户图片列表
     */
    @RequestMapping("")
    public String index(Model model) {
        //multipart 是否多选
        model.addAttribute("multipart", getPara("multipart"));
        //图片宽度
        model.addAttribute("w", getPara("w"));
        //图片高度
        model.addAttribute("h", getPara("h"));
        //图片缩小比例
        model.addAttribute("scale", getPara("scale"));
        //上传路径
        model.addAttribute("imgPath", getPara("imgPath"));
        return PREFIX + "image_list.html";
    }

    /**
     * 查询用户图片列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list() {
        return ConstantFactory.me().getUsersImageList(ShiroKit.getUser().getId());
    }

    /**
     * @Auther:Victor
     * @Description:上传图片
     * @Date:Create in 12:42 2018/4/21
     * @Modified By:
     */
    @RequestMapping(value = "/upload")
    @ResponseBody
    public Object upload(@RequestParam("dir") String dir, MultipartHttpServletRequest req) throws Exception {
        synchronized (lockObj) {
            Map<String, Object> _return = new HashMap<>();
            Map<String, MultipartFile> fileMap = req.getFileMap();
            if (ToolUtil.isNotEmpty(fileMap)) {
                Iterator iterator = fileMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    String imgPath = "";
                    try {
                        Map.Entry<String, MultipartFile> entry = (Map.Entry<String, MultipartFile>) iterator.next();
                        MultipartFile mFile = entry.getValue();
                        //文件根目录
                        String fileRoot = victorProperties.getFileUploadPath();
                        File file = new File(victorProperties.getFileUploadTempPath() + mFile.getOriginalFilename());
                        mFile.transferTo(file);
                        String uuid = "";

                        uuid = String.valueOf(new Date().getTime());

                        //新文件名称
                        StringBuilder newFileName = new StringBuilder(fileRoot).append(dir)
                                .append(File.separator).append(dateFormat.format(new Date())).append(File.separator).append(uuid)
                                .append(FileUtil.getSuffix(file.getName()));
                        //处理文件 缩略
                        imgPath = processFile(file, newFileName.toString(), fileRoot);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (ToolUtil.isNotEmpty(imgPath)) {
                        imgPath = File.separator + Const.FILE_PREFIX + File.separator + imgPath;
                        imgPath = imgPath.replace("\\", "/");//将\改为/ 否则小程序不识别
                        Integer userid = ShiroKit.getUser().getId();
                        UsersImages image = new UsersImages();
                        image.setCreatetime(new Date());
                        image.setImgPath(imgPath);
                        image.setUserid(userid);
                        usersImagesMapper.insert(image);
                        _return.put("imgPath", image.getImgPath());
                        clearCache(CacheKey.USERS_IMAGE_LIST + userid);
                    }
                    break;

                }
            }

            return JSON.toJSON(_return);
        }
    }


}
